package com.zjun.demo.experimentaldemo.honeycomb

import android.graphics.Point
import android.graphics.PointF

object PointInPolygon {

    /**
     * 判断点是否在多边形内
     */
    fun isPointInsidePolygon(pointLat: Double, pointLon: Double, polygonLatLons: Array<PointF>): Boolean {
        var intersectCount = 0
        val polygonSize = polygonLatLons.size
        for (i in 0 until polygonSize) {
            val lat1 = polygonLatLons[i].x
            val lon1 = polygonLatLons[i].y
            val lat2 = polygonLatLons[(i + 1) % polygonSize].x
            val lon2 = polygonLatLons[(i + 1) % polygonSize].y
            if (rayCastIntersect(pointLat, pointLon, lat1.toDouble(), lon1.toDouble(), lat2.toDouble(), lon2.toDouble())) {
                intersectCount++
            }
        }
        return intersectCount % 2 == 1 // 奇数次相交则点在多边形内
    }

    /**
     * 射线与直线的交点判断
     */
    private fun rayCastIntersect(pointLat: Double, pointLon: Double, lat1: Double, lon1: Double, lat2: Double, lon2: Double): Boolean {
        if (lat1 == lat2) {
            return false // 垂直情况下不处理
        }
        if (pointLon >= lon1.coerceAtMost(lon2) && pointLon <= lon1.coerceAtLeast(lon2)) {
            val intersectFraction = (pointLon - lon1) / (lon2 - lon1)
            val intersectY = lat1 + (lat2 - lat1) * intersectFraction
            if (intersectY > pointLat) {
                return true // 存在交点且在点的下方
            }
        }
        return false
    }

    @JvmStatic
    fun main(args: Array<String>) {
        val pointLat = 34.05
        val pointLon = -118.25
        val polygonLatLons = mutableListOf<PointF>()
        val inside = isPointInsidePolygon(pointLat, pointLon, polygonLatLons.toTypedArray())
        println("Point is inside polygon: $inside")
    }

}